use axum::{extract::{Path, State}, Json};
use serde::Deserialize;
use sqlx::{Pool, Sqlite};

use crate::db::{get_user_counter, CounterRecord};

use super::{jwt::Claims, ApiError};


#[derive(Deserialize)]
pub struct AddPayload {
    counter_id: i32,
    step: i32,
}

//添加计数器的历史记录
pub async fn add(
    claims: Claims,
    State(pool): State<Pool<Sqlite>>,
    Json(payload): Json<AddPayload>,
) -> Result<Json<serde_json::Value>, ApiError> {
    let user_id = claims.get_user_id();
    let counter = get_user_counter(payload.counter_id, user_id, &pool).await?;
    let next_value = counter.value + payload.step;
    sqlx::query(
        r#"insert into counter_records (counter_id, step, begin, end) values (?, ?, ?, ?);update counters set value = ?, updated_at = CURRENT_TIMESTAMP where id = ?"#,
        )
        .bind(payload.counter_id)
        .bind(payload.step)
        .bind(counter.value)
        .bind(next_value)
        .bind(next_value)
        .bind(payload.counter_id)
        .execute(&pool)
        .await?;

    Ok(Json(serde_json::json!({"message": "ok"})))
}

//获取计数器的历史记录
pub async fn list(
    Path(counter_id): Path<i32>,
    claims: Claims,
    State(pool): State<Pool<Sqlite>>,
) -> Result<Json<Vec<CounterRecord>>, ApiError> {
    let user_id = claims.get_user_id();
    get_user_counter(counter_id, user_id, &pool).await?;

    let records = sqlx::query_as::<_, CounterRecord>(
        "select * from counter_records where counter_id = ? order by id desc",
        )
        .bind(counter_id)
        .fetch_all(&pool)
        .await?;

    Ok(Json(records))
}
